package com.afs.electronicforensics.adapter;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.afs.electronicforensics.activity.ShowActivity;
import com.afs.electronicforensics.adapter.viewholder.IVViewHolder;
import com.afs.electronicforensics.entity.FileInfo;
import com.afs.electronicforensics.activity.R;
import com.afs.electronicforensics.entity.MessagePage;
import com.afs.electronicforensics.entity.Result;
import com.afs.electronicforensics.fragment.RecordCloudFragment;
import com.afs.electronicforensics.monitor.FileUpMonitorEditText;
import com.afs.electronicforensics.utils.Constants;
import com.afs.electronicforensics.utils.FileTypeUtil;
import com.afs.electronicforensics.utils.FileUtil;
import com.afs.electronicforensics.utils.OssManager;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class AlbumLocalAdapter extends RecyclerView.Adapter<IVViewHolder>{
    private ArrayList<FileInfo> items;
    private MyItemClickListener listener;
    private View view;
    private Context context;
    private Result mResult = new Result();
    private Dialog dialog;

    public AlbumLocalAdapter(Context context, ArrayList<FileInfo> items) {
        this.context=context;
        this.items = items;
    }

    @NonNull
    @NotNull
    @Override
    public IVViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        view= LayoutInflater.from(parent.getContext()).inflate(R.layout.iv_item,parent,false);
        IVViewHolder holder = new IVViewHolder(view,listener);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull IVViewHolder holder, int position) {
        FileInfo currentItem=items.get(position);
        // 这里可以用Glide等网络图片加载库
        Glide.with(view).load(currentItem.getUrl()).into(holder.imageView);

        holder.textView.setText(currentItem.getTitle());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog = new Dialog(context,R.style.Dialog_Fullscreen);
                LayoutInflater inflater = LayoutInflater.from(context);
                view = inflater.inflate(R.layout.image_dialog, null);
                dialog.setContentView(view);
                dialog.create();
                dialog.show();

                ImageView iv = view.findViewById(R.id.my_image);

                EditText imageName = view.findViewById(R.id.image_name);
                EditText imageRemark = view.findViewById(R.id.image_remark);

                TextView upDown = view.findViewById(R.id.image_up_down);
                TextView modify = view.findViewById(R.id.image_modify);
                TextView delete = view.findViewById(R.id.image_delete);
                TextView cancel = view.findViewById(R.id.image_cancel);

                modify.setVisibility(View.GONE);
                Glide.with(view).load(currentItem.getUrl()).into(iv);
                System.out.println(currentItem.getUrl());
                upDown.setText("上传");

                new FileUpMonitorEditText().SetMonitorEditText(upDown,imageName,imageRemark);


                upDown.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String name = imageName.getText().toString().trim();
                        String content = imageRemark.getText().toString().trim();
                        //获取文件后缀名
                        String substring =currentItem.getTitle().substring(currentItem.getTitle().lastIndexOf(".") + 1);
                        int type = FileTypeUtil.getType(substring);
                        String ossUrl =Constants.URL_ROOT+"file/findOne?messageName=" + name +"." + substring+"&type="+type+"&userId="+Constants.USER_ROOT.getUid();
                        new FindMessage(name,type,currentItem.getUrl(),content).execute(ossUrl);
                        dialog.dismiss();
                    }
                });
                delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (FileUtil.deleteFile(currentItem.getUrl())){
                            items.remove(currentItem);
                            notifyDataSetChanged();
                            Toast.makeText(context,"删除成功",Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(context,"删除失败",Toast.LENGTH_SHORT).show();
                        }
                        dialog.dismiss();
                    }
                });
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });
            }
        });
    }


    public void setOnItemClickListener(MyItemClickListener listener) {
        this.listener = listener;
    }



    @Override
    public int getItemCount() {
        return items.size();
    }
    private class FindMessage extends AsyncTask {
        private String name;
        private String fileUrl;
        private int filetype;
        private String content;
        public FindMessage(String name, int filetype, String fileUrl, String content) {
            this.name = name;
            this.filetype = filetype;
            this.fileUrl = fileUrl;
            this.content = content;
        }
        @Override
        protected Object doInBackground(Object[] params) {
            String path = params[0].toString();
            try {
                //以get方式提交整个路径
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");//设置请求方式为get
                conn.setConnectTimeout(5000);

                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String str = br.readLine();
                    return str;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            // TODO Auto-generated method stub
            String info = o.toString().trim();
            try {
                JSONObject js = new JSONObject(info);
                String code = js.getString("code");
                System.out.println(code);
                if("1".equals(code)){
                    Toast.makeText(context,"文件已经存在",Toast.LENGTH_SHORT).show();

                }else{
                    OssManager.getInstance().init(view.getContext()).uploadOss(name,fileUrl, Constants.USER_ROOT.getUsername(),content);
                    Toast.makeText(context,"上传成功",Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

}
